﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DormMS.IService;
using DormMS.Model;
using DormMS.Model.SearchModels;
using Infrastructure.Dao;
using SqlSugar;

namespace DormMS.Service
{
    public class SysCodeService : ISysCodeService
    {
        private SqlSugarClient db;

        /// <summary>
        /// 通过代码名称和代码类型取代码
        /// </summary>
        /// <param name="CodeType"></param>
        /// <param name="CodeName"></param>
        /// <returns></returns>
        public SysCode GetSysCodeByCodeNameAndCodeType(string CodeType, string CodeName)
        {
            using (db = DbConfig.GetInstance())
            {
                db.CurrentFilterKey = "";
                var data = db.Queryable<SysCode>().SingleOrDefault(x => x.CodeType == CodeType && x.CodeName == CodeName);
                return data;
            }
        }

        /// <summary>
        /// 通过代码和代码类型取代码名称
        /// </summary>
        /// <param name="CodeType"></param>
        /// <param name="Code"></param>
        /// <returns></returns>
        public SysCode GetSysCodeByCodeNameAndCode(string CodeType, int Code)
        {
            using (db = DbConfig.GetInstance())
            {
                db.CurrentFilterKey = "";
                var data = db.Queryable<SysCode>().SingleOrDefault(x => x.CodeType == CodeType && x.Code == Code);
                return data;
            }
        }

        /// <summary>
        /// 通过代码类型取代码信息
        /// </summary>
        /// <param name="CodeType"></param>
        /// <returns></returns>
        public List<SysCode> GetSysCodeByCodeType(string CodeType)
        {
            using (db = DbConfig.GetInstance())
            {
                db.CurrentFilterKey = "";
                var data = db.Queryable<SysCode>().Where(x => x.CodeType == CodeType).ToList();
                return data;
            }
        }
        /// <summary>
        /// 通过代码查找方式取代码对应值
        /// </summary>
        /// <param name="search"></param>
        /// <param name="total"></param>
        /// <returns></returns>
        public List<SysCode> GetSysCodeList(SysCodeSearchModel search, ref int total)
        {
            using (db = DbConfig.GetInstance())
            {
                db.CurrentFilterKey = "";
                search.OrderByFields = search.OrderByFields;
                var data = db.Queryable<SysCode>();
                if (string.IsNullOrEmpty(search.Keywords) == false)
                {
                    data = data.Where<SysCode>(x => x.CodeType == search.Keywords);
                }

                var list = data.Select<SysCode>((x) => new SysCode { CodeType = x.CodeType, CodeName = x.CodeName, Code = x.Code, Status = x.Status }).OrderBy(search.OrderByFields).ToPageList(search.Skip / search.Take + 1, search.Take, ref total);

                return list;
            }
        }

    }
}
